package net.hvacapp.cmvrfforandroid.ui.mine;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import com.mirror.android.common.util.ScreenUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.ViewDetailActivity;
import net.hvacapp.cmvrfforandroid.ui.mine.model.GetNoticeDataResp;
import net.hvacapp.cmvrfforandroid.ui.mine.model.NoticeData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.DateTimeUtils;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.OnRefreshListener;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenu;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuCreator;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuItem;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuLayout;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuListView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Map;

@EActivity(R.layout.activity_notice_manager)
public class NoticeManagerActivity extends BaseActivity {

    private final int Add_New_Notice = 1;

    private Dialog mProgressDlg;

    @ViewById(R.id.lv_templete)
    SwipeMenuListView mTempleteLv;

    private int beginIndex = 0;
    private int endIndex = 0;

    private QuickAdapter<NoticeData> mQuickAdapter;



    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(0, "公告管理", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AnnotationUtil.get(MainTabBarActivity.class));
            }
        });

//        int ids[] = {R.id.action_new_notice};
//        int icons[] = {R.drawable.new_project};
//        setupToolbarMenuItem(ids, icons, new String[]{"添加公告"}, null);
        setButton1Info("添加公告", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(NoticeManagerActivity.this, AnnotationUtil.get(PublishActivity.class));
                        intent.putExtra("type", 0);
                        startActivityForResult(intent, Add_New_Notice);
                    }
                }
        );


        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<NoticeData>(context, R.layout.notice_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, NoticeData item) {
                    helper.setVisible(R.id.iv_navi, true);
                    helper.setVisible(R.id.iv_new, false);
                    helper.setText(R.id.tv_title, item.getTitle());
                    helper.setText(R.id.tv_info, item.getContent());
                    helper.setText(R.id.tv_date, DateTimeUtils.getDate(item.getTime()));
                    helper.setText(R.id.tv_from, item.getFrom());
//                    helper.setText(R.id.tv_title, item.getName());
//                    helper.setText(R.id.tv_description, NumberUtil.formateDouble(item.getArea()) + "平米 " + NumberUtil.formateDouble(item.getLoad()) + "W");
                }
            };
        }

        mTempleteLv.setAdapter(mQuickAdapter);

        // 设置左侧滑menu
        SwipeMenuCreator menuCreator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem menuItem = new SwipeMenuItem(NoticeManagerActivity.this);
                menuItem.setBackground(new ColorDrawable(Color.parseColor("#FFBA7F")));
                menuItem.setWidth((int) ScreenUtils.dpToPx(NoticeManagerActivity.this, 80));
                menuItem.setTitleColor(getResources().getColor(R.color.cm_navigation_red_color));
                menuItem.setTitleSize(14);
                menu.addMenuItem(menuItem);
                menuItem.setTitle("删除");

//                if (menu.getViewType() == ArticleAdapter.ARTICLE_NOT_READ) {
//                    menuItem.setIcon(R.drawable.information_center_mark_article_read_icon);
//                    menuItem.setTitle("标为已读");
//
//                } else if (menu.getViewType() == ArticleAdapter.ARTICLE_READ) {
//                    menuItem.setIcon(R.drawable.information_center_mark_article_not_read_icon);
//                    menuItem.setTitle("标为未读");
//                }
            }
        };
        mTempleteLv.setMenuCreator(menuCreator);
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        beginIndex = 0;
        endIndex = Constant.PAGE_COUNT - 1;
        loadAllNotices(beginIndex, endIndex);
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    /**
     * toolbar上的按钮点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new_notice:

                Intent intent = new Intent(this, AnnotationUtil.get(PublishActivity.class));
                intent.putExtra("type", 0);
                startActivityForResult(intent, Add_New_Notice);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initEvent() {

        mTempleteLv.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                // 下拉刷新
                beginIndex = 0;
                endIndex = Constant.PAGE_COUNT - 1;
                loadAllNotices(beginIndex, endIndex);
            }

            @Override
            public void onPullUpRefresh() {
                // 上拉加载
                beginIndex = mQuickAdapter.getCount();
                endIndex = beginIndex + Constant.PAGE_COUNT - 1;
                loadAllNotices(beginIndex, endIndex);
            }
        });

        mTempleteLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NoticeData data = (NoticeData) parent.getItemAtPosition(position);
                Intent intent = new Intent(NoticeManagerActivity.this, AnnotationUtil.get(ViewDetailActivity.class));
                intent.putExtra("type", 0);
                intent.putExtra("title", data.getTitle());
                intent.putExtra("info", data.getFrom() + " " + DateTimeUtils.getDate(data.getTime()));
                intent.putExtra("content", data.getContent());
                intent.putExtra("id", data.getGuidId());
                startActivity(intent);
            }
        });

        mTempleteLv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(SwipeMenuLayout swipeMenuLayout, int position, SwipeMenu menu, int index) {
                NoticeData notice = mQuickAdapter.getItem(position);
                deleteOneNotice(notice);
                return true;
            }
        });


    }


    private void loadAllNotices(final int si, int ei) {
        Map<String, Object> param = new HashMap<>();
        param.put("si", si);
        param.put("ei", ei);
        param.put("os", 1);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_NOTICES, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetNoticeDataResp>() {
            @Override
            public void onSuccess(GetNoticeDataResp obj) {
                // 成功
                if (si == 0) {
                    mQuickAdapter.clear();
                }
                mQuickAdapter.addAll(obj.getGetPostResult());
                mTempleteLv.onRefreshComplete();
            }

            @Override
            public void onFailure(String response) {
                showMessage("获取房间列表失败，请重试！");
                mTempleteLv.onRefreshComplete();
            }
        });
    }


    private void deleteOneNotice(final NoticeData notice) {

        Map<String, Object> param = new HashMap<>();
        param.put("id", notice.getGuidId());

        mProgressDlg = createProgressBarDialog(this, "删除公告中...");
        mProgressDlg.show();

        BasicHttpClient.httpDeleteAsync(HttpConstant.HTTP_DELETE_ONE_NOTICE, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetNoticeDataResp>() {
            @Override
            public void onSuccess(GetNoticeDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                mQuickAdapter.remove(notice);
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("删除公告失败，请重试！");
            }
        });
    }



    /**
     * 回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != this.RESULT_OK) {
            return;
        }
        if (requestCode == Add_New_Notice) {
            loadAllNotices(0, -1);
        }
    }


}
